{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "# Advanced settings for WHFast:  Extra speed, accuracy, and additional forces\n",
    "\n",
    "There are several performance enhancements one can make to WHFast.  However, each one has pitfalls that an inexperienced user can unwittingly fall into.  We therefore chose safe default settings that make the integrator difficult to misuse.  **This makes the default WHFast substantially slower and less accurate than it can be**.  Here we describe how to alter the integrator settings to improve WHFast's performance.\n",
    "\n",
    "**TL;DR**\n",
    "\n",
    "As long as \n",
    "\n",
    "1. you don't add, remove or otherwise modify particles between timesteps\n",
    "2. you get your outputs by passing a list of output times ahead of time and access the `particles` pointer between calls to `sim.integrate()` (see, e.g., the Visualization section of [WHFast.ipynb](../WHFast))\n",
    "\n",
    "you can set `sim.ri_whfast.safe_mode = 0` to get a substantial performance boost.  Under the same stipulations, you can set `sim.ri_whfast.corrector = 11` to get much higher accuracy, at a nearly negligible loss of performance (as long as there are many timesteps between outputs).\n",
    "\n",
    "If you want to modify particles, or if the code breaks with these advanced settings, read below for details, and check out the Common mistake with WHFast section at the bottom of [WHFast.ipynb](../WHFast)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "**The Wisdom-Holman algorithm**\n",
    "\n",
    "In order to understand and apply the various integrator flags, we need to first understand the Wisdom-Holman scheme (see, e.g., Wisdom & Holman 1991, or Rein & Tamayo 2015 for more details).\n",
    "\n",
    "The Wisdom-Holman algorithm consists of alternating *Keplerian* steps that evolve particles on their two-body Keplerian orbits around the star with *interaction* steps that apply impulses to the particles' velocities from the interactions between bodies.  The basic algorithm for a single timestep $dt$ is a Leapfrog Drift-Kick-Drift scheme with an *interaction* kick over the full $dt$ sandwiched between half timesteps of *Keplerian* drift:\n",
    "\n",
    "$H_{Kepler}(dt/2)\\:H_{Interaction}(dt)\\:H_{Kepler}(dt/2)$\n",
    "\n",
    "Timesteps like the one above are then concatenated over the full integration:\n",
    "\n",
    "$H_{Kepler}(dt/2)\\:H_{Interaction}(dt)\\:H_{Kepler}(dt/2)$ $H_{Kepler}(dt/2)\\:H_{Interaction}(dt)\\:H_{Kepler}(dt/2)$ ... $H_{Kepler}(dt/2)\\:H_{Interaction}(dt)\\:H_{Kepler}(dt/2)$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "**Combining Kepler steps and synchronizing**\n",
    "\n",
    "It turns out that Kepler steps take longer than interaction steps as long as you don't have many planets, so an obvious and important performance boost would be to combine adjacent Kepler half-steps into full ones, i.e.:\n",
    "\n",
    "$H_{Kepler}(dt/2)\\:H_{Interaction}(dt)\\:H_{Kepler}(dt)\\:H_{Interaction}(dt)\\:H_{Kepler}(dt) ... \\:H_{Interaction}(dt)\\:H_{Kepler}(dt/2)$\n",
    "\n",
    "The issue is that if you were to, say, output the state of the particles as the simulation progressed, the positions would not correspond to anything real, since the beginning (or end) of one of the full $H_{Kepler}(dt)$ steps corresponds to some intermediate step in an abstract sequence of calculations for a given timestep.  In order to get the particles' actual positions, we would have to calculate to the end the timestep we want the output for by splitting a full *Kepler* step back into two half-steps, e.g.,\n",
    "\n",
    "$H_{Kepler}(dt/2)\\:H_{Interaction}(dt)\\:H_{Kepler}(dt)\\:H_{Interaction}(dt)\\:H_{Kepler}(dt/2) \\text{**PRINT OUTPUT**} H_{Kepler}(dt/2) H_{Interaction}(dt)\\:H_{Kepler}(dt)$...\n",
    "\n",
    "We call this step of reinserting half-Kepler steps to obtain the physical state of the particles *synchronizing*.  This must be done whenever the **actual** states of the particles are required, e.g., before every output, or if one wanted to use the particles' states to compute additional changes to the particle orbits between timesteps.  It is also necessary to synchronize each timestep whenever the MEGNO chaos indicator is being computed.\n",
    "\n",
    "**Conversions between Jacobi and Inertial Coordinates**\n",
    "\n",
    "It turns out that the most convenient coordinate system to work in for performing the Kepler steps is often Jacobi coordinates (see, e.g., 9.5.4 of Murray & Dermott).  WHFast therefore works in Jacobi coordinates by default, converting to inertial coordinates when it needs to (e.g. for output, and for doing the direct gravity calculation in the interaction step, which is most easily done in inertial coordinates).\n",
    "\n",
    "One feature of WHFast is that it works in whatever inertial coordinate system you choose for your initial conditions.  This means that whatever happens behind the scenes, the user always gets the particles' inertial coordinates at the front end.  At the beginning of every timestep, WHFast therefore has to somehow obtain the Jacobi coordinates.  The straightforward thing would be to convert from the inertial coordinates to Jacobi coordinates every timestep, but these conversions slow things down, and they represent extra operations that grow the round-off error.\n",
    "\n",
    "WHFast therefore stores the Jacobi coordinates internally throughout the time it is running, and only recalculates Jacobi coordinates from the inertial ones if told to do so.  Since Jacobi coordinates reference particles to the center of mass of all the particles with indices lower than their own (typically all the particles interior to them), the main reason you would have to recalculate Jacobi coordinates is if between timesteps you choose to somehow change the particles' positions or velocities (give them kicks in addition to their mutual gravity), or change the particles' masses.  \n",
    "\n",
    "**Overriding the defaults**\n",
    "\n",
    "Let's begin by importing rebound, and defining a simple function to reset rebound and initialize a new simulation with a test case,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "import rebound\n",
    "import numpy as np\n",
    "def test_case():\n",
    "    sim = rebound.Simulation()\n",
    "    sim.integrator = 'whfast'\n",
    "    sim.add(m=1.) # add the Sun\n",
    "    sim.add(m=3.e-6,e=0.99, a=1.) # add Earth\n",
    "    sim.move_to_com()\n",
    "    sim.dt = 0.2\n",
    "    return sim"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "By default WHFast synchronizes and recalculates the Jacobi coordinates from the inertial ones every timestep.  This guarantees that the user always gets physical particle states for output, and ensures reliable output if the user decides to, e.g., grow the particles' masses between timesteps.  \n",
    "\n",
    "Now that you understand the pitfalls, if you want to boost WHFast's performance, you simply set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "sim = test_case()\n",
    "sim.ri_whfast.safe_mode = 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Now it becomes the user's responsibility to appropriately synchronize and recalculate jacobi coordinates when needed.  You can tell WHFast to recalculate Jacobi coordinates for a given timestep (say after you change a particle's mass) with the `sim.ri_whfast.recalculate_coordinates_this_timestep` flag.  After it recalculates Jacobi coordinates, WHFast will reset this flag to zero, so you just set it each time you mess with the particles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "safe_mode = 1\n",
      "---------------------------------\n",
      "REBOUND version:     \t3.4.0\n",
      "REBOUND built on:    \tMay 31 2017 11:53:50\n",
      "Number of particles: \t2\n",
      "Selected integrator: \twhfast\n",
      "Simulation time:     \t6.2831853071795858e+05\n",
      "Current timestep:    \t0.200000\n",
      "---------------------------------\n",
      "<rebound.Particle object, m=1.0 x=3.8952737650111065e-06 y=-4.025686466113066e-07 z=0.0 vx=2.1862005456099384e-06 vy=9.999414128270949e-08 vz=0.0>\n",
      "<rebound.Particle object, m=3e-06 x=-1.2984227143844442 y=0.1341896612527594 z=0.0 vx=-0.7287335151973472 vy=-0.0333313804272124 vz=0.0>\n",
      "---------------------------------\n",
      "Safe integration took 1.4043679237365723 seconds\n",
      "---------------------------------\n",
      "REBOUND version:     \t3.4.0\n",
      "REBOUND built on:    \tMay 31 2017 11:53:50\n",
      "Number of particles: \t2\n",
      "Selected integrator: \twhfast\n",
      "Simulation time:     \t6.2831853071795858e+05\n",
      "Current timestep:    \t0.200000\n",
      "---------------------------------\n",
      "<rebound.Particle object, m=1.0 x=3.89491388755522e-06 y=-4.0258518356289257e-07 z=0.0 vx=2.18648433924743e-06 vy=9.996480978405334e-08 vz=0.0>\n",
      "<rebound.Particle object, m=3e-06 x=-1.298304629185073 y=0.13419506118763086 z=0.0 vx=-0.7288281130824766 vy=-0.03332160326135111 vz=0.0>\n",
      "---------------------------------\n",
      "Manual integration took 0.8836901187896729 seconds\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "Porb = 2*np.pi # orbital period for Earth, using units of G = 1, solar masses, AU and yr/2pi\n",
    "\n",
    "sim = test_case()\n",
    "print(\"safe_mode = {0}\".format(sim.ri_whfast.safe_mode))\n",
    "start_time = time.time()\n",
    "sim.integrate(1.e5*Porb)\n",
    "sim.status()\n",
    "print(\"Safe integration took {0} seconds\".format(time.time() - start_time))\n",
    "\n",
    "sim = test_case()\n",
    "sim.ri_whfast.safe_mode = 0\n",
    "start_time = time.time()\n",
    "sim.integrate(1.e5*Porb)\n",
    "sim.status()\n",
    "print(\"Manual integration took {0} seconds\".format(time.time() - start_time))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "source": [
    "In our test case with a single planet, there is effectively no interaction step, and by combining Kepler steps we get almost the full factor of 2 speedup we expect.  Because Kepler steps are expensive (by virtue of having to solve the transcendental Kepler equation), this will always be an important performance boost for few-planet cases.\n",
    "\n",
    "Note that one case where REBOUND needs to synchronize every timestep is if you're using the MEGNO chaos indicator.  So if you call"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "sim.init_megno()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "REBOUND will synchronize every timestep even if you set `sim.ri_whfast.safe_mode = 0` and never explicitly call `sim.integrator_synchronize()`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "source": [
    "**Modifying particles/forces**\n",
    "\n",
    "Again, if performance is a factor in your simulations, you would not want to write a custom stepper in python that modifies the particles, since this will be very slow.  You could either write a modified C version of `reb_simulation_integrate` in `src/librebound.c` (the flags are defined in `librebound.h`, and have the same name as the python ones, just without `sim.` in front), or you can use the REBOUNDXF library, which takes care of this for you and supports many typically used modifications.  We again illustrate a simple scheme with python code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "sim = test_case()\n",
    "sim.ri_whfast.safe_mode = 0\n",
    "def integrate_mod(sim, t_final):\n",
    "    while sim.t < t_final:\n",
    "        sim.step()\n",
    "        sim.particles[1].m += 1.e-10\n",
    "        sim.ri_whfast.recalculate_coordinates_this_timestep = 1\n",
    "    sim.integrator_synchronize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Here, because we grow the mass of the planet every timestep, we have to recalculate Jacobi coordinates every timestep (since they depend on the masses of the particles).  We therefore manually set the flag to recalculate them the next timestep every time we make a change.  Here we would actually get the same result if we just left `sim.ri_whfast.safe_mode = 1`, since when recalculating Jacobi coordinates, WHFast automatically has to synchronize in order to get real positions and velocities for the planets.  In this case WHFast is therefore synchronizing and recalculating Jacobi coordinates every timestep.\n",
    "\n",
    "But imagine now that instead of growing the mass, we continually add an impulse to vx:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "sim = test_case()\n",
    "sim.ri_whfast.safe_mode = 0\n",
    "def integrate_mod(sim, t_final):\n",
    "    while sim.t < t_final:\n",
    "        sim.step()\n",
    "        sim.particles[1].vx += 1.e-10*sim.dt\n",
    "        sim.ri_whfast.recalculate_coordinates_this_timestep = 1\n",
    "    sim.integrator_synchronize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "This would not give accurate results, because the `sim.particles[1].vx` we access after `sim.step()` isn't a physical velocity (it's missing a half-Kepler step).  It's basically at an intermediate point in the calculation.  In order to make this work, one would call `sim.integrator_synchronize()` between `sim.step()` and accessing `sim.particles[1].vx`, to ensure the velocity is physical."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "**Symplectic correctors**\n",
    "\n",
    "Symplectic correctors make the Wisdom-Holman scheme higher order (without symplectic correctors it's second order).  The great thing about them is that they only need to get applied when you synchronize.  So if you just need to synchronize to output, and there are many timesteps between outputs, they represent a very small performance loss for a huge boost in accuracy (compare for example the green line (11th order corrector) to the red line (no corrector) in Fig. 4 of Rein & Tamayo 2015--beyond the right of the plot, where the round-off errors dominate, the two lines would rise in unison).  We have implemented symplectic correctors up to order 11.  You can set the order with (must be an odd number), e.g.,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "sim.ri_whfast.corrector = 11"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "By default, WHFast does not use correctors, i.e., sim.integrator_whfast_corrector = 0.  This is because the default is also to synchronize every timestep.  An Nth order corrector does N-1 Kepler steps of various sizes, so an 11th order corrector done every timestep would increase the number of Kepler steps by an order of magnitude, making WHFast unacceptably slow.  So keep in mind that if you're doing modifications that require recalculating jacobi coordinates or synchronizing every timestep, you should turn off symplectic correctors (the default) unless you really need the accuracy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Changing the internal coordinate system**\n",
    "\n",
    "WHFast by default uses Jacobi coordinates internally. This works well for planetary systems which are stable and orbits are not crossing. However, in some cases a different coordinate system might perform better. WHFast also support so-called democratic heliocentric coordinates and the so called WHDS coordinates. For more information on these coordinates systems [see Hernandez and Dehnen (2016)](https://arxiv.org/abs/1612.05329). To select a different coordinate system, use the following syntax:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sim.ri_whfast.coordinates = 'jacobi' #default\n",
    "sim.ri_whfast.coordinates = 'democraticheliocentric' \n",
    "sim.ri_whfast.coordinates = 'whds' "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that symplectic corrector are only compatible with Jacobi coordinates because both democratic heliocentric and WHDS include a so called jump step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "**Warning messages**\n",
    "\n",
    "If you choose a timestep that is larger than the smallest dynamical timescale and WHFast has difficulties to solve the Kepler problem, you will receive a warning message."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/rein/git/rebound/rebound/simulation.py:305: RuntimeWarning: WHFast convergence issue. Timestep is larger than at least one orbital period.\n",
      "  warnings.warn(msg[1:], RuntimeWarning)\n"
     ]
    }
   ],
   "source": [
    "sim = test_case()\n",
    "sim.dt = 1000.\n",
    "sim.integrate(1000.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
